package com.ac.scum.log.task.face;

import jakarta.annotation.PostConstruct;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RKeys;
import org.redisson.api.RedissonClient;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

@Slf4j
@Component
@AllArgsConstructor
public class InitLock {

    private final RedisTemplate<String, Object> redisTemplate;
    private final RedissonClient redissonClient;

    @PostConstruct
    public void clearAllRedissonLocks() {
        String lockKeyPattern = "log-upd-task::*";
        try {
            RKeys rKeys = redissonClient.getKeys();
            Iterable<String> keys = rKeys.getKeysByPattern(lockKeyPattern);

            for (String key : keys) {
                if (!deleteKey(key)) {
                    log.error("Failed to delete key: " + key);
                }
            }
        } catch (Exception e) {
            log.error("Exception occurred while clearing Redisson locks {} ", e.getMessage(), e);
        }
        log.info("deleted all lock");

    }


    @SuppressWarnings("deprecation")
    private boolean deleteKey(String key) {
        Long deletedCount = redisTemplate.execute((RedisConnection connection) -> connection.del(key.getBytes()));
        return deletedCount != null && deletedCount > 0;
    }
}
